开发这个功能主要是刚开始要备份几台windows服务器的用户数据,后来写到最后就变成了一个数据备份通用工具了,程序可以根据配置文件的配置进行目录数据的备份,只要指定备份的目录,程序会自动调用系统winrar命令将目录自动生成压缩包,然后自动将压缩包数据上传到一台ftp服务器上,实现自动备份功能,因为是调用的winrar命令,所以要求系统中必须安装winrar,要介绍的基本就这么多,接下来我们开始介绍程序的配置和功能:
配置文件cfg.ini:
1 2 3 4 5 6 7 8 9 10 11 12 13 |
[server] address = 192.168.1.1 port = 2258 [user] user = cat password = Test [upload] back_target = e:\\webadmin\\web\\flaskr [winrar_path] rar_path = C:\\"Program Files"\\WinRAR\\ |
配置文件功能分四部分
1、[server]段用来配置要备份的ftp地址和端口
2、[user]段部分用来设置连接ftp的用户和密码
3、[upload]段用来配置你需要备份的目录,因为python识别windows目录是双”\\”,所以写目录是要用两个斜杠表示目录
4、[winrar_path]段用来设置windwos系统中winrar的安装目录,双斜杠功能同upload段,且“Program Files” 的双引号不能删除。
python代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 |
#coding=utf-8 import time import os.path import re import ConfigParser from ftplib import FTP import subprocess from subprocess import Popen,PIPE cf = ConfigParser.ConfigParser() cf.read('cfg.ini') ftp_server = cf.get('server', 'address') ftp_port = cf.get('server', 'port') username = cf.get('user', 'user') password = cf.get('user', 'password') cmd_path = cf.get('winrar_path', 'rar_path') cmd_rar = 'rar a -r ' back_target = cf.get('upload', 'back_target') #save_path = cf.get('upload', 'save_path') #str_cmd = 'C:\\"Program Files"\\WinRAR\\rar.exe a -r' + ' e:\\webadmin' + time.strftime('%Y%m%d%H%M%S') + '.rar' + ' e:\\webadmin' str_cmd = cmd_path + cmd_rar + back_target + time.strftime('%Y%m%d%H') + '.rar ' + back_target pattern = '100%' def rar_file(): p = subprocess.Popen(str_cmd, shell=True, stdout=PIPE, stderr=PIPE) stdout,stderror=p.communicate() match = re.search(pattern, stdout) if match.start(): return 'ok' def ftp_conn(): ftp = FTP() ftp.connect(ftp_server, ftp_port) return ftp def ftp_upload(): ftp = ftp_conn() ftp.login(username,password) remotepath = os.path.basename(back_target) + time.strftime('%Y%m%d%H') + '.rar' bufsize = 1024 localpath = os.path.dirname(back_target) + '\\'+ os.path.basename(back_target) + time.strftime('%Y%m%d%H') + '.rar' fp = open(localpath,'rb') ftp.storbinary('STOR '+ remotepath ,fp,bufsize) fp.close() ftp.quit() # def ftp_download(): # ftp = ftp_conn() # ftp.set_debuglevel(2) # ftp.connect(ftp_server,2258) # ftp.login(username,password) # #ftp.set_pasv(1) # remotepath =r'/MyIPSec.ipsec' # bufsize = 1024 # localpath =r'e:\i\MyIPSec.ipsec' # fp = open(localpath,'wb') # ftp.retrbinary('RETR '+ remotepath ,fp.write,bufsize) # fp.close() # ftp.quit() if __name__ == '__main__': status = rar_file() if status == 'ok': ftp_upload() |
今天代码就不逐行解释了,都比较简单,另外为了方便大家使用,方便每个人使用,我制作了exe版本,需要的兄弟可以直接下载使用,下载地址:http://www.mindg.cn/download/winback_data_to_ftp.zip ,使用中有任何问题,可随时联系我。